package com.backpack;

public class LongestPalindromicSubsequence0120_516 {
    public int longestPalindromeSubseq(String s) {
        //动态规划是
        //dp 含义：表示下标范围[i,j]范围内的子字符串中的回文子串的长度
        int[][] dp = new int[s.length()][s.length()];
        //返回值 dp[0][s.length()-1]
        //初始化：dp[i][0] = 1;
//        for (int i = 0; i < s.length(); i++) {
//            dp[i][0] =1;
//        }

        //遍历顺序:因为 dp[i][j] 依赖于 dp[i+1][j-1] ,所以 二维数组从下往上、从左往右遍历
        //遍历公式
        for (int i = s.length()-2; i >=0; i--) {
            for (int j = i; j <= s.length()-1; j++) {
                if(s.charAt(i) == s.charAt(j)){
                    if(j-i>=1) dp[i][j] = dp[i+1][j-1] + 2;
                    else dp[i][j] =1;
                } else {
                    dp[i][j] = Math.max(dp[i][j-1],dp[i+1][j]);
                }
            }
        }

        return dp[0][s.length()-1];
    }
}
